package com.ysu.shop.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ysu.shop.pojo.User;
import com.ysu.shop.service.IUserService;
import com.ysu.shop.utils.JwtUtil;
import com.ysu.shop.utils.Result;
import com.ysu.shop.utils.ShaUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Map;

@RestController
public class LoginController {

    @Resource
    private IUserService userService;

    @PostMapping("/login")
    public Result login(@RequestBody Map<String,Object> param){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", param.get("username")).eq("password", ShaUtil.getSHA256(param.get("password").toString()));
        User user =  userService.getOne(wrapper);
        if (user == null){
            return Result.getFailResult(null,"用户名或密码错误");
        }
        if (user.getActive() == 0) {
            return Result.getFailResult(null,"请联系管理员帮你激活");
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("token", JwtUtil.create(user));
        jsonObject.put("id",user.getId());
        return Result.getSuccessResult(jsonObject,"登录成功");
    }


}